import Web3 from 'web3'

import {useWeb3React} from '@web3-react/core'
import {ethers} from 'ethers'
import {Web3Provider} from '@ethersproject/providers'
import React, {FC, useState, useEffect} from 'react'
import {Button} from '@mui/material'

interface WalletProps {
  address: string
  balance: number
}
const Connection = window?.ethereum

// let provider =new Web3Provider(Connection)
// let providers2= new ethers.providers.Web3Provider(Connection);
let provider = new ethers.providers.Web3Provider(Connection)
// const web3 = new Web3(Web3.givenProvider || 'http://localhost:8000');
// // let web3 = new Web3(Connection);
// if (typeof Connection !== 'undefined') {
//    provider  =new Web3Provider(Connection)
//   // 使用 Connection 访问以太坊钱包
//     // 等待 MetaMask 授权
//     Connection.enable().then(console.log);;
//   //  Connection.request({ method: 'eth_requestAccounts' })
//   // .then(console.log);
// } else {
//   // 提示用户安装以太坊钱包
//   window.open('https://chrome.google.com/webstore/detail/metamask/nkbihfbeogaeaoehlefnkodbefgpgknn')
// }
export const disconnec = async () => {
  // 断开钱包连接

  // 判断是否存在钱包链接对象
  if (Connection) {
    try {
      // 请求注销用户
      // 私有 API，仅在 MetaMask 中可用
      Connection._metamask.isEnabled = false
      // 请求清除访问权限
      await Connection.request({
        method: 'wallet_requestPermissions',
        params: [{eth_accounts: {}}],
      })
      console.log('已断开 MetaMask 连接！')
    } catch (error) {
      console.error('注销用户失败！', error)
    }
  } else {
    console.error('无法连接钱包！')
  }
}
export const useConnection = async () => {
  useEffect(() => {
    const connection = async () => {
      if (typeof Connection !== 'undefined') {
        const signer = provider.getSigner()
        console.log(signer, 'signer')
      } else {
        window.open(
          'https://chrome.google.com/webstore/detail/metamask/nkbihfbeogaeaoehlefnkodbefgpgknn'
        )
      }
    }
    connection()
  }, [])
}
//获取账户余额。您可以使用以下代码获取账户余额：

export const useAccounts = (): WalletProps => {
  const [address, setAddress] = useState<string>('')
  const [balance, setBalance] = useState<number>(0)

  useEffect(() => {
    const loadWallet = async () => {
      if (provider) {
        const accounts = await provider.listAccounts()
        setAddress(accounts[0])
        console.log(accounts, 'accounts', provider)
        const weiBalance = await provider.getBalance(accounts[0])

        const etherBalance = ethers.utils.formatEther(weiBalance)
        setBalance(parseFloat(etherBalance))
      }
    }

    loadWallet()
  }, [])

  return {address, balance}
}

//添加Chain节点：
export const addChain = (chainId: string) => {
  Connection.request({
    method: 'wallet_addEthereumChain',
    params: [
      {
        chainId: '0x3',
        chainName: 'mainnet Test Network',
        nativeCurrency: {
          name: 'Ether',
          symbol: 'ETH',
          decimals: 18,
        },
        rpcUrls: [
          'https://mainnet.infura.io/v3/c9483a89286b4ead99113990dfebb734',
        ],
        blockExplorerUrls: ['https://goerli.infura.io'],
      },
    ],
  })
}
// 切换Ethereum/Rinkeby节点，切换时页面将刷新。
export const useSwitchChain = async () => {
  console.log(provider, 'provider')
  try {
    const {chainId} = provider._network
    const newChainId = chainId === 1 ? 42220 : 5 // Switch between Ethereum Mainnet and Rinkeby
    await Connection.request({
      method: 'wallet_switchEthereumChain',
      params: [{chainId: `0x${newChainId.toString(16)}`}],
    })
  } catch (error) {
    try {
      await Connection.request({
        method: 'wallet_addEthereumChain',
        params: [
          {
            chainId: '0x42220',
            chainName: 'Rinkeby Test Network',
            rpcUrls: ['https://celo-mainnet.infura.io/'],
            blockExplorerUrl: 'https://celo-mainnet.infura.io',
            iconUrls: [
              'https://cdn.iconscout.com/icon/free/png-256/metamask-2728406-2261818.png',
            ],
          },
        ],
      })
      console.log('Switched to Rinkeby network')
    } catch (error) {}
  }
}

//链接钱包获取地址和余额
export const useWallet = (): [
  WalletProps | null,
  () => Promise<void>,
  () => Promise<void>
] => {
  const [wallet, setWallet] = useState<WalletProps | null>(null)
  const [provider, setProvider] =
    useState<ethers.providers.JsonRpcProvider | null>(null)
  const connectWallet = async () => {
    if (typeof window.ethereum === 'undefined') {
      window.open(
        'https://chrome.google.com/webstore/detail/metamask/nkbihfbeogaeaoehlefnkodbefgpgknn'
      )
      return
    }

    const provider = new ethers.providers.Web3Provider(window.ethereum)
    // const provider = new ethers.providers.JsonRpcProvider(window.ethereum);
    // console.log('Google',provider,provider.getSigner(), await provider.listAccounts())
    Connection.enable()
    const accounts = await provider.listAccounts()
    const balance = accounts && (await provider.getBalance(accounts[0]))
    // const signer = provider.getSigner();
    const address = accounts[0]
    // console.log('Google',provider,signer,'Wallets',provider.listAccounts() )
    setProvider(provider)
    setWallet({
      address,
      balance: parseFloat(ethers.utils.formatEther(balance)),
    })
  }
  useEffect(() => {
    connectWallet()
  }, [])

  const disconnectWallet = async () => {
    if (provider) {
      try {
        provider.removeAllListeners()
        await provider.send('wallet_requestPermissions', [{eth_accounts: {}}])
        await provider.send('wallet_removePermissions', [])
        setProvider(null)
        setWallet(null)
      } catch (error) {
        console.error('注销用户失败！', error)
      }
    } else {
      console.error('无法连接钱包！')
    }
  }

  return [wallet, disconnectWallet, connectWallet]
}
//获取签名
export const useAccountSignature = (): [string | null, () => Promise<void>] => {
  const [signature, setSignature] = useState<string | null>(null)

  const getSignature = async () => {
    const signer = provider.getSigner()
    const message = '我是帅哥'
    const signature = await signer.signMessage(message)
    setSignature(signature)
  }

  return [signature, getSignature]
}
